package cn.sccl.dirms.security.controller;

import cn.sccl.common.model.PageResult;
import cn.sccl.common.util.DataBaseUtils;
import cn.sccl.common.util.ExcelExportUtils;
import cn.sccl.common.util.PropertiesUtil;
import cn.sccl.common.web.BaseController;
import cn.sccl.dirms.security.model.User;
import cn.sccl.dirms.security.model.UserExtend;
import cn.sccl.dirms.security.model.UserPrincipal;
import cn.sccl.dirms.security.model.UserPrincipalDetails;
import cn.sccl.dirms.security.service.UserManager;
import cn.sccl.dirms.topo.util.MD5;
import com.fasterxml.jackson.annotation.JsonView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Created by 杨浩宇 on 2016-02-24.
 */
@RestController
@RequestMapping(value = "/dirms/security/user")
public class UserController extends BaseController {

    @Autowired
    private UserManager userManager;

    /**
     * 显示所有数据
     */
    @RequestMapping(value = "/all", method = RequestMethod.GET)
    public List<User> listAllUser() {
        return userManager.listAll();
    }

    @RequestMapping(value = "/{name}", method = RequestMethod.GET)
    public User findUser(@PathVariable("name") String name) {
        return userManager.findByName(name);
    }

    @RequestMapping(value = "/data/{id}", method = RequestMethod.GET)
    public List<User> findUserData(@PathVariable("id") String id) {
        return userManager.findUserData(id);
    }


    /**
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/data/exist/{id}", method = RequestMethod.GET)
    public PageResult<UserExtend> findExistUserDataOfRole(@PathVariable("id") String id, HttpServletRequest request) {
        return userManager.findExistUserDataOfRole(id,getPageIndex(request),getPageSize(request));
    }

    /**
     * 根据角色id 查找 可分配的用户
     * @param id
     * @return
     */
    @RequestMapping(value = "/data/available/{id}", method = RequestMethod.GET)
    public PageResult<User> findAvailableUserDataOfRole(@PathVariable("id") String id,HttpServletRequest request) {
        return userManager.findAvailableUserDataOfRole(id,getPageIndex(request),getPageSize(request));
    }

    @RequestMapping(value = "/userData/{username}", method = RequestMethod.GET)
    public List<User> findUserDataByName(@PathVariable("username") String name) {
        return userManager.findUserDataByName(name);
    }

    @RequestMapping(value = "/userOfRole/{name}/{id}", method = RequestMethod.GET)
    public List<User> findUserOfRole(@PathVariable("name") String name, @PathVariable("id") String id) {
        return userManager.findUserOfRole(name, id);
    }


    /**
     * 分页查询
     *
     * @param pageIndex 页码
     * @param pageSize  分页大小
     * @param request
     * @return
     */
    @RequestMapping(value = "/page/{pageIndex}/{pageSize}", method = RequestMethod.GET)
    public PageResult<User> pageQueryUser(@PathVariable("pageIndex") long pageIndex, @PathVariable("pageSize") int pageSize, HttpServletRequest request) {
        return userManager.pageQueryByLike(pageIndex, pageSize, getQueryData(request));
    }

    /**
     * 用户数据分页查询
     *
     * @param request
     * @return
     */
    @RequestMapping(value = "/query", method = RequestMethod.GET)
    public PageResult<User> QueryUser(HttpServletRequest request) {
        String start = request.getParameter("page");// 起始页
        String limit = request.getParameter("rows");// 每页数量
        if (start == null || start == "") {
            start = "0";
        }
        if (limit == null || limit == "") {
            limit = "10";
        }
        Long pageIndex = Long.parseLong(start);
        int pageSize = Integer.parseInt(limit);

        return userManager.pageQueryByLike(pageIndex, pageSize, getQueryData(request));
    }

    /**
     * 保存数据
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "/", method = RequestMethod.POST)
    public User saveUser(@RequestBody User user) {
        if (StringUtils.isEmpty(user.getPassword())) {
            String defaultPassWord = PropertiesUtil.getString("defaultPassWord");
            user.setPassword(defaultPassWord);
        }
        userManager.save(user);
        return user;
    }

    /**
     * 根据ID删除数据
     *
     * @param id
     */
//    @RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
    @RequestMapping(value = "/{id}", method = {RequestMethod.POST,RequestMethod.GET})
    @JsonView(Object.class)
    public boolean deleteUser(@PathVariable("id") String id) {
        userManager.delete(id);
        return true ;
    }

    @RequestMapping(value = "/validateLogin", method = RequestMethod.POST)
    public UserPrincipalDetails validateLogin(@RequestBody UserPrincipalDetails userPrincipal, HttpServletRequest request) {
        User user = userManager.findUniqueBy(DataBaseUtils.Model2HashMap(userPrincipal));

        if (user != null) {
            userPrincipal.setToken(userPrincipal.getName() + "_" + userPrincipal.getPassword());
            userPrincipal.setUserName(user.getUserName());
            request.getSession().setAttribute("userPrincipal", userPrincipal);
            return userPrincipal;
        } else {
            return null;
        }
    }

    @RequestMapping(value = "resetpw", method = RequestMethod.POST)
    @JsonView(Object.class)
    public void reSetPW(HttpServletRequest request) {
        String id = request.getParameter("id");
        String defaultPassWord = PropertiesUtil.getString("defaultPassWord");
        if (id != null) {

            User user = userManager.get(id);
            if (user != null) {
                user.setPassword(defaultPassWord);
                userManager.update(user);
            }

        }

    }


    @RequestMapping(value = "/findUserPrincipal", method = RequestMethod.GET)
    public List<UserPrincipal> findUserPrincipal(){
        return userManager.findUserPrincipal(null);
    }

    /**
     * 导出数据为excel
     *
     * @param excelTitle 标题行json数据
     * @param type       0：查全部  1：查当前页  默认查全部
     * @param request
     * @param response
     */
    @RequestMapping(value = "/export/{type}", method = RequestMethod.POST)
    public void export(String excelTitle, @PathVariable("type") Integer type, HttpServletRequest request, HttpServletResponse response) {
        List data = null;
        //查询行数据
        if (type == 1) {
            PageResult<User> res = userManager.pageQueryByLike(getPageIndex(request), getPageSize(request), getQueryData(request));
            data = res != null ? res.getRows() : null;
        } else {
            data = userManager.findByLike(getQueryData(request));
        }
        //导出excel
        ExcelExportUtils.export(excelTitle, data, request, response);
    }

    /**
     * 修改用户密码
     */
    @RequestMapping(value = "editpw", method = RequestMethod.POST)
    @JsonView(Object.class)
    public UserPrincipal editPW(HttpServletRequest request) {
        String id = request.getParameter("id");
        String pw1 = request.getParameter("password");
        String newpw = request.getParameter("newpw");
        User user = userManager.getUser(id);
        String pw2 = user.getPassword();
        boolean flag = false;

        if (MD5.getInstance().getMD5(pw1).equals(pw2)) {//数据库存储的是加密字符串时修改加密字符串
            user.setPassword(MD5.getInstance().getMD5(newpw));
            userManager.update(user);
            flag = true;
        } else if (pw1.equals(pw2)) {//数据库密码没有加密，则保存原密码
            user.setPassword(newpw);
            userManager.update(user);
            flag = true;
        }
        if(flag){
            UserPrincipal userPrincpal = new UserPrincipal();
            userPrincpal.setId(user.getId());
            userPrincpal.setName(user.getName());
            userPrincpal.setUserName(user.getUserName());
            userPrincpal.setToken(user.getName() + "_" + user.getPassword());
            return userPrincpal;
        }else{
            return null;
        }
    }
}
